package com.ilikesoup.instant.enums.loader;

import com.ilikesoup.instant.enums.basic.SelectEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;

/**
 * 通过在指定包下，通过类名查找下拉枚举
 *
 * @author Soup
 */
public class SelectEnumPackageScanner extends SelectEnumFinder {

    private static final Logger logger = LoggerFactory.getLogger(SelectEnumPackageScanner.class);

    private final String[] scanPackages;

    public SelectEnumPackageScanner(String scanPackages) {
        this.scanPackages = new String[]{scanPackages};
    }

    public SelectEnumPackageScanner(String[] scanPackages) {
        this.scanPackages = scanPackages;
    }

    @Override
    @SuppressWarnings("unchecked")
    protected Class<? extends Enum<?>> find(String key) {
        for (String scanPackage : scanPackages) {
            try {
                Class<?> clazz = Class.forName(getEnumClassName(scanPackage, key));
                if (clazz.isEnum() && SelectEnum.class.isAssignableFrom(clazz)) {
                    logger.debug("找到SelectEnum，查找键：{}，结果：{}", key, clazz);
                    return (Class<? extends Enum<?>>) clazz;
                }
            } catch (Exception e) {
                // ignore
            }
        }
        logger.debug("未找到SelectEnum，扫描包：{}，查找键：{}", Arrays.toString(scanPackages), key);
        return null;
    }

    private String getEnumClassName(String pkg, String key) {
        return pkg + "." + key;
    }
}
